package cn.com.controller;

import cn.com.domain.FilesEntity;
import cn.com.domain.vo.FilesVo;
import cn.com.service.FilesService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import cn.com.response.BaseResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author CRL
 * @Date 2021/4/18 23:14
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/file")
public class FilesController {

    @Value("${file.attachRootPath}")
    private String attachRootPath;

    @Value("${file.url}")
    public String fileUrl;

    @Autowired
    private FilesService filesService;

    /**
     * 上传文件
     *
     * @param request  request
     * @param response response
     * @return Map
     */
    @ApiOperation(value = "上传文件")
    @PostMapping("/upload")
    @ResponseBody
    public BaseResponse<FilesVo> upload(HttpServletRequest request, HttpServletResponse response) {
        return getFilesVoBaseResponse(request);
    }

    /**
     * 下载文件
     *
     * @param date
     * @param file
     * @param request
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "文件下载/展示")
    @ResponseBody
    @RequestMapping(value = "/download/{date}/{file:[a-zA-Z0-9_\\\\.]+}", method = RequestMethod.GET)
    public void download(@PathVariable("date") String date, @PathVariable("file") String file,
                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName = request.getParameter("fileName");
        String[] strings = file.split("\\.");
        //String fileName = strings[0];//md5转码作为文件名
        System.out.print("文件名==" + fileName);
        if (fileName == null) {
            fileName = file;
        }
        String fileType = "txt";
        if (strings.length > 1) {
            fileType = strings[1];
        }
        this.filesService.download(response, attachRootPath + "/" + date + "/" + file, fileType, fileName);
    }

    private BaseResponse<FilesVo> getFilesVoBaseResponse(HttpServletRequest request) {
        FilesVo filesVo = new FilesVo();
        FilesEntity files = filesService.upload(request);
        filesVo.setFilename(files.getFilename2());
        filesVo.setOldName(files.getFilename());
        filesVo.setUrl(fileUrl + files.getFilepath());
        filesVo.setRelativeUrl(files.getFilepath());
        filesVo.setFilesize(files.getFilesize());
        filesVo.setId(String.valueOf(files.getId()));
        return new BaseResponse<>(filesVo);
    }
}
